package com.prtek.reminder.util;

import android.graphics.drawable.AnimationDrawable;
import android.graphics.drawable.Drawable;
import android.media.MediaPlayer;
import android.text.TextUtils;

/**
 * Created by jarly on 2018/10/25.
 */

public class AudioPlayer {

  private MediaPlayer mMediaPlayer;
  private AnimationDrawable mAnimationDrawable;

  private static AudioPlayer mAudioPlayer;
  private String mFilePath;

  public static AudioPlayer getInstance() {
    if (mAudioPlayer == null) {
      synchronized (AudioPlayer.class) {
        mAudioPlayer = new AudioPlayer();

      }
    }
    return mAudioPlayer;
  }

  public void startPlayAudio(Drawable drawable, String filePath) {
    if (TextUtils.equals(mFilePath, filePath)) {
      stop();
      return;
    }

    if (mMediaPlayer == null) {
      mMediaPlayer = new MediaPlayer();

    }

    if (mMediaPlayer.isPlaying()) {
      stop();
      mMediaPlayer = new MediaPlayer();
    }
    mFilePath = filePath;
    mAnimationDrawable = (AnimationDrawable) drawable;

    mMediaPlayer.setOnCompletionListener(mp -> release());
    try {
      mMediaPlayer.reset();
      mMediaPlayer.setDataSource(filePath);
      mMediaPlayer.prepare();
    } catch (Exception e) {
      e.printStackTrace();
    }
    mMediaPlayer.start();
    mAnimationDrawable.start();
  }

  public void stop() {
    if (mAnimationDrawable == null || mMediaPlayer == null) {
      return;
    }

    mMediaPlayer.stop();
    release();
  }

  private void release() {
    mAnimationDrawable.selectDrawable(0);
    mAnimationDrawable.stop();
    mMediaPlayer.release();
    mMediaPlayer = null;
    mFilePath = "";
  }
}
